<template>
  <div>
    <catch-table ref="catchTableRef" :columns="columns" :api="api" :search-form="search" :exports="false" :operation="true" exportUrl="dc/task/export" permission="dataCheck@dcTask">
      <template #dialog="row">
        <Create :primary="row?.id" :api="api" />
      </template>
      <template #source_file_state="scope">
        <el-tooltip popper-class="tooltip-box" effect="dark" :disabled="scope.row.source_file_state !== 4" :content="scope.row.source_file_remark" placement="top-start">
          <el-tag :type="getFileStateTag(scope.row.source_file_state)">{{ getFileStateText(scope.row.source_file_state) }}</el-tag>
        </el-tooltip>
      </template>
      <template #task_state="scope">
        <el-tooltip popper-class="tooltip-box" effect="dark" :disabled="scope.row.task_state !== 5 && scope.row.task_state !== 65" :content="scope.row.task_remark" placement="top-start">
          <el-tag :type="getTaskStateTag(scope.row.task_state)"
            >{{ getTaskStateText(scope.row.task_state) }}<span v-if="scope.row.task_state === 3 && scope.row.process !== undefined">（{{ scope.row.process }}%）</span></el-tag
          >
        </el-tooltip>
      </template>
      <template #operate="scope">
        <PermissionButton v-if="isShowDestroy(scope.row)" permission="dataCheck@dcTask@destroy" type="danger" icon="trash" size="small" text class="ml-2" @click="destroyHandle(scope.row)">
          删除
        </PermissionButton>
        <PermissionButton v-if="isShowUpdate(scope.row)" permission="dataCheck@dcTask@update" type="primary" icon="pencil-square" size="small" text class="ml-2" @click="updateHandle(scope.row)">
          编辑
        </PermissionButton>

        <PermissionButton
          v-if="isShowExecCheck(scope.row)"
          :loading="scope.row.isCheckLoading"
          permission="dataCheck@dcTask@update"
          type="success"
          size="small"
          :icon="scope.row.task_state === TASK_STATE.PENDING ? 'play' : 'arrow-path'"
          text
          class="ml-2"
          @click="execCheck(scope.row)"
        >
          {{ scope.row.task_state === TASK_STATE.PENDING ? '开始核对' : '重新核对' }}
        </PermissionButton>

        <!-- 停止核对：仅当task_state=2或3时显示 -->
        <PermissionButton
          v-if="isTaskChecking(scope.row.task_state)"
          :loading="scope.row.isStopLoading"
          permission="dataCheck@dcTask@stop"
          type="warning"
          size="small"
          icon="stop"
          text
          class="ml-2"
          @click="stopCheck(scope.row)"
        >
          停止核对
        </PermissionButton>

        <!-- 下载：仅当task_state=4时显示 -->
        <PermissionButton
          v-if="scope.row.task_state === TASK_STATE.COMPLETED"
          permission="dataCheck@download@execute"
          icon="arrow-down-tray"
          type="primary"
          size="small"
          text
          class="ml-2"
          :loading="scope.row.isDownloadLoading"
          @click="downloadDataResult(scope.row)"
        >
          下载
        </PermissionButton>
      </template>

      <template #file_download_count="scope">
        <span class="text-blue-500 transition-colors duration-200 cursor-pointer hover:text-blue-600 hover:underline" @click="handleDownloadCountClick(scope.row)">
          {{ scope.row.file_download_count || 0 }}
        </span>
      </template>
    </catch-table>

    <!-- 下载记录抽屉 -->
    <DownloadRecordDrawer v-model="drawerVisible" :task-id="selectedTaskId" :task-name="selectedTaskName" />

    <!-- 进度弹窗 -->
    <ProgressDialog v-model="progressDialogVisible" :task-id="currentTaskId" :task-name="currentTaskName" @task-stopped="handleTaskStopped" @close="handleProgressDialogClose" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, defineAsyncComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { usePermission } from '@/composables/usePermission'
import http from '@/support/http'
import type { TaskRow, CatchTableInstance } from './types'
import { usePolling } from './composables/usePolling'
import { useStatusUpdate } from './composables/useStatusUpdate'
import { TASK_STATE, getTaskStateTag, getFileStateTag, getTaskStateText, isShowDestroy, getFileStateText, isTaskChecking, isShowExecCheck, isShowUpdate } from './constants'

// 异步组件加载
const Create = defineAsyncComponent(() => import('./form/create.vue'))
const DownloadRecordDrawer = defineAsyncComponent(() => import('./components/DownloadRecordDrawer.vue'))
const ProgressDialog = defineAsyncComponent(() => import('./components/ProgressDialog.vue'))
const PermissionButton = defineAsyncComponent(() => import('@/components/PermissionButton.vue'))

const api = 'dc/task'

// catch-table 组件引用
const catchTableRef = ref<CatchTableInstance | null>(null)

// 使用轮询管理
const sourceFilePolling = usePolling()
const taskStatusPolling = usePolling()

// 使用状态更新逻辑
const { updateSourceFileStatus, updateTaskStatus } = useStatusUpdate(catchTableRef)

// 抽屉状态管理
const drawerVisible = ref(false)
const selectedTaskId = ref<number | null>(null)
const selectedTaskName = ref<string>('')

// 进度弹窗状态管理
const progressDialogVisible = ref(false)
const currentTaskId = ref<number | null>(null)
const currentTaskName = ref<string>('')

// 使用权限检查 Composable
const { debugPermissions } = usePermission()

/**
 * 更新处理方法
 */
const updateHandle = (row: any) => {
  catchTableRef.value?.openDialog(row, '编辑')
}

/**
 * 删除处理方法
 */
const destroyHandle = (row: any) => {
  catchTableRef.value?.del(api, row.id)
}

// 打印权限调试信息并启动轮询
onMounted(() => {
  debugPermissions('数据核对任务管理', ['dataCheck@DcTask@downloadResult', 'dataCheck@DcTask@downloadDataResult', 'dataCheck@dcTask@downloadRecord'])

  // 启动总表状态轮询
  sourceFilePolling.startPolling(() => {
    return sourceFilePolling.executeUpdate(updateSourceFileStatus)
  }, 2000)

  // 启动任务状态轮询
  taskStatusPolling.startPolling(() => {
    return taskStatusPolling.executeUpdate(updateTaskStatus)
  }, 2000)
})

/**
 * 下载结果方法
 */
const downloadDataResult = async (row: TaskRow) => {
  try {
    row.isDownloadLoading = true
    const response = await http.post('/dc/download/execute', {
      task_id: row.task_id
    })
    if (response.data.code === 10000) {
      window.open(response.data.data.file_download_url, '_blank')
      catchTableRef.value?.doSearch()
    } else {
      ElMessage.error(response.data.message || '数据结果下载失败')
    }
  } catch (error) {
    console.error('数据结果下载失败:', error)
    ElMessage.error('数据结果下载失败，请稍后重试')
  } finally {
    row.isDownloadLoading = false
  }
}

/**
 * 查看下载记录方法
 */
const viewDownloadRecord = (row: TaskRow) => {
  selectedTaskId.value = row.task_id
  selectedTaskName.value = row.task_name
  drawerVisible.value = true
}

/**
 * 处理下载数点击
 */
const handleDownloadCountClick = (row: TaskRow) => {
  if (!row.file_download_count || row.file_download_count === 0) {
    ElMessage.warning('暂无下载数据')
    return
  }
  viewDownloadRecord(row)
}

/**
 * 开始核对方法
 */
const execCheck = async (row: TaskRow) => {
  try {
    row.isCheckLoading = true
    const response = await http.post('/dc/check/start', {
      task_id: row.task_id
    })

    if (response.data.code === 10000) {
      currentTaskId.value = row.task_id
      currentTaskName.value = row.task_name
      progressDialogVisible.value = true
      // catchTableRef.value?.doSearch()
    } else {
      ElMessage.error(response.data.message || '启动核对任务失败')
    }
  } catch (error) {
    console.error('启动核对任务失败:', error)
    ElMessage.error('启动核对任务失败，请稍后重试')
  } finally {
    row.isCheckLoading = false
  }
}

/**
 * 停止核对方法
 */
const stopCheck = async (row: TaskRow) => {
  try {
    row.isStopLoading = true
    const response = await http.post('/dc/check/stop', {
      task_id: row.task_id
    })

    if (response.data.code === 10000) {
      ElMessage.success('停止核对任务成功')
      catchTableRef.value?.doSearch()
    } else {
      ElMessage.error(response.data.message || '停止核对任务失败')
    }
  } catch (error) {
    console.error('停止核对任务失败:', error)
    ElMessage.error('停止核对任务失败，请稍后重试')
  } finally {
    row.isStopLoading = false
  }
}

/**
 * 处理任务停止事件
 */
const handleTaskStopped = () => {
  currentTaskId.value = null
  currentTaskName.value = ''
  catchTableRef.value?.doSearch()
}
const handleProgressDialogClose = () => {
  catchTableRef.value?.doSearch()
}
// table columns
const columns = [
  {
    prop: 'serial_number',
    label: '编号',
    width: 80
  },
  {
    prop: 'task_name',
    label: '任务名称'
  },
  {
    prop: 'target_file_original_name',
    label: '核对表名称'
  },
  {
    prop: 'source_file_original_name',
    label: '总表名称'
  },
  {
    prop: 'source_file_state',
    label: '总表状态',
    width: 140,
    slot: 'source_file_state'
  },
  {
    prop: 'task_state',
    label: '任务状态',
    width: 140,
    slot: 'task_state'
  },
  {
    prop: 'file_download_count',
    label: '下载数',
    width: 120,
    slot: 'file_download_count'
  },
  {
    prop: 'creator',
    label: '创建人',
    width: 150
  },
  {
    prop: 'created_at',
    label: '创建时间'
  },
  {
    type: 'operate',
    label: '操作',
    width: 280,
    update: false,
    destroy: false,
    show: true
  }
]
// table search
const search = [
  {
    type: 'input',
    name: 'task_name',
    label: '任务名称'
  },
  {
    type: 'select',
    name: 'task_state',
    label: '任务状态',
    options: [
      { label: getTaskStateText(TASK_STATE.PENDING), value: TASK_STATE.PENDING },
      // { label: getTaskStateText(TASK_STATE.QUEUING), value: TASK_STATE.QUEUING },
      { label: getTaskStateText(TASK_STATE.CHECKING), value: TASK_STATE.CHECKING },
      { label: getTaskStateText(TASK_STATE.COMPLETED), value: TASK_STATE.COMPLETED },
      { label: getTaskStateText(TASK_STATE.FAILED), value: TASK_STATE.FAILED },
      { label: getTaskStateText(TASK_STATE.STOPPED), value: TASK_STATE.STOPPED }
      // { label: getTaskStateText(TASK_STATE.STOPPED_COMPLETED), value: TASK_STATE.STOPPED_COMPLETED },
      // { label: getTaskStateText(TASK_STATE.STOPPED_FAILED), value: TASK_STATE.STOPPED_FAILED }
    ]
  }
]
</script>
